"use strict"

module.exports = function(app, settings){
	let log4js 			= require('log4js')
			,_					= require('lodash')
			,util 			= require('util')
			,url 				= require('url')
			,cookieParser = require('cookie-parser')
			,debug			= require('debug')('identity')
			,logger 		= log4js.getLogger()
			,constants 	= require("./constants")()
			,models 		= app.locals.models;


	app.set('views', './routes/identity/views');

	let host 		= settings.host; /* system host name, e.g. aivics.net */
	//account subapp handle all frontend authentication requests
	/** Step-1: extract DOMAIN and Client from request
	*	domain name can be found in three places
			1. first sector of the full domain name, e.g. qywx-admin.aivics.net, qywx-dmin is the domain
			2. In the query parameter authub_domain, e.g. http://localhost/oauth/token?authub_domain=qywx-admin
			3. In the request header "X-Authub-Domain"
	*/
	function getDomainAndAccount(req){
		let domain = false;
		let account = false;

		var requestHost = _.split(req.get('host'), ":", 1);

		debug("request host: ", requestHost);
		debug("config host: ", host);

		if(requestHost !== 'localhost' && _.endsWith(requestHost, host)){

			var reqdomains 	= _.split(requestHost, ".");;
			var hostDomains = _.split(host, ".");

			var level = reqdomains.length - hostDomains.length;
			if(level === 2){
				domain = reqdomains[0];
				account = reqdomains[1];
				return [domain, account];
			}
		}
		//If domain not part of hostname
		domain = req.query[constants.PARAM_DOMAIN_NAME];
		account = req.query[constants.PARAM_ACCOUNT_NAME];

		debug("domain", domain, 'account', account);
		if(!_.isEmpty(domain) && !_.isEmpty(account))
			return [domain, account];

		//If not in query parameters
		domain = req.get(constants.HEADER_DOMAIN_NAME);
		account = req.get(constants.HEADER_ACCOUNT_NAME);
		if(!_.isEmpty(domain) && !_.isEmpty(account))
			return [domain, account];

		return null; //Finally if nothing found, return null
	}

	app.use(function(req, res, next){
		let domainAndAccount = getDomainAndAccount(req);

		if(!domainAndAccount){
			return res.status(500).json({
				success: false,
				errCode: 500,
				errMsg: "can_not_proceeding_with_invalid_domain"
			});
		}

		//Get configurations of the domain from MongoDB
		let Domain = models.Domain;
		Domain.findOne({ name: domainAndAccount[0] }, function(err, domain){
			if(err){
				logger.error("find domain error: ", err);
				return res.status(500).json({
					success: false,
					errCode: 500,
					errMsg: 'failed_to_find_domain'
				});
			}

			if(domain === null){
				return res.status(500).json({
					success: false,
					errCode: 500,
					errMsg: "can_not_proceeding_with_invalid_domain"
				});
			}

			debug("domain: ", domainAndAccount);

			res.locals.domain 	= domain;
			res.locals.account 	= domainAndAccount[1];

			return next();
		});
	});

	require("./oauth2")(app, settings);
};
